<script setup>
import {onMounted, ref, reactive} from "vue";
import {Search} from "@element-plus/icons-vue";
import service from "@/service/service";
import ParameterSettings from './zhiling/ZhiLingParameterSettings.vue'
import {
  getSatelliteListSerive,
  canProtocolListSerive,
  InstructTypesSerive,
  getInstructionsOfTypeSerive,
  ShengChengZhiLingCodeSerive,
  duoxingFaSongZhiLingSerive,

} from "@/api/satellite/SingleInstructionSending.js"

// import service from '@/utils/request'

import router from "@/router";
import {listDept} from "@/api/system/dept.js";
import {delSatellitemanage} from "@/api/satellite/satellitemanage.js";
import Sortable from 'sortablejs'


const tableRef = ref()     // 指向 el-table
const tableData2 = ref([])

const {proxy} = getCurrentInstance()
//import {ElMessage} from "element-plus";

const activeName = ref('')

let subSystemTypes = ref([]);
let instructList = ref([]);
let showInstruct = ref(false);
let satelliteList = ref([]);
let selectedSatelliteId = ref([]);
let selectedSatelliteCode = ref("");
let selectedSatelliteData = ref("");
// 声明一个值为"0"的字符串
const zeroStr = ref('0');

let tableData = reactive([]);
/*let satelliteData = ref("");
let instructionName = ref("");*/
let instructionContent = ref([]);
let absoluteDelayed = ref([{}, {}]);
let dateShow = ref([false, false, false]);
let historyData = ref([]);

let totals = ref(10);
let currentPage = ref(1);
let pageSize = ref(10);

// 参数设置  添加 以下变量
const parameterDialogVisible = ref(false)
const currentInstructionCode = ref('')
const currentInstructionName = ref('')
const currentSatelliteId = ref('')
const selectedSatelliteCodes = ref('')
const currentSatelliteIds = ref([])




// 新增：用于保存Sortable实例，方便后续销毁
const sortableInstance = ref(null);
// 打开参数设置对话框的方法
const openParameterSettings = (instructionCode, instructionName) => {
  if (!selectedSatelliteId.value || selectedSatelliteId.value.length === 0) {
    ElMessage.warning('请先选择卫星')
    return
  }

  currentInstructionCode.value = instructionCode
  currentInstructionName.value = instructionName
  currentSatelliteId.value = selectedSatelliteId.value[0]
  currentSatelliteIds.value = selectedSatelliteId.value
  selectedSatelliteCodes.value = weixingBianHaos(selectedSatelliteData.value)
  parameterDialogVisible.value = true
}

// 处理选中的卫星编号，返回一个数组
const weixingBianHaos = (selectedSatelliteData) => {
  // 可以在这里处理参数保存后的逻辑
  console.log('参数已保存:@@@@@@@@@@!!!!!!!!!!!!!!!!!', selectedSatelliteData)
  // 结果：['XAE2509', 'aaaa']
  const codeList = computed(() =>
      selectedSatelliteData.map(item => item.split(';@;')[1])
  );
  return codeList.value
}


// 参数保存后的回调
const handleParametersSaved = (parameters) => {
  // 可以在这里处理参数保存后的逻辑
  console.log('参数已保存:', parameters)
}


const getSatelliteList = (currentPage, pageSize) => {

  if (currentPage <= 0) {
    currentPage = 1;
  }

  if (pageSize <= 0) {
    pageSize = 10;
  }

  getSatelliteListSerive(currentPage, pageSize).then(response => {


    satelliteList.value = response.data.records;
    totals.value = response.data.totals;
  }).catch((error) => {
    alert(JSON.stringify(error))
  })
};

// 新增：封装拖拽初始化函数
const initSortable = () => {
  // 1. 先销毁旧的Sortable实例（避免重复绑定）
  if (sortableInstance.value) {
    sortableInstance.value.destroy();
    sortableInstance.value = null;
  }

  // 2. 确保tableRef和tbody存在（DOM已渲染）
  nextTick(() => {
    const tbody = tableRef.value?.$el.querySelector('.el-table__body-wrapper tbody');
    if (!tbody) return;

    // 3. 创建新的Sortable实例并保存到ref中
    sortableInstance.value = Sortable.create(tbody, {
      animation: 150,
      ghostClass: 'sortable-ghost',
      onEnd: (evt) => {
        // 调整数组顺序（逻辑不变）
        const { oldIndex, newIndex } = evt;
        const [moved] = tableData.splice(oldIndex, 1);
        tableData.splice(newIndex, 0, moved);
      }
    });
  });
};

onMounted(() => {
  getSatelliteList(currentPage.value, pageSize.value);
  // 首次初始化拖拽（调用封装函数）
  initSortable();
})
// 新增一个用于强制刷新的key
const collapseKey = ref(0);
const getSubSystemTypes = async () => {

  let selectedSatellite = selectedSatelliteData.value + "";
  let satelliteIdCode = selectedSatellite.split(",");
  if (selectedSatellite === "" || satelliteIdCode.length <= 0) {
    subSystemTypes.value = [];
    return;
  }

  selectedSatelliteCode.value = "";
  selectedSatelliteId.value = [];
  for (let i = 0; i < satelliteIdCode.length; i++) {
    let singleIdCodeStr = satelliteIdCode[i];
    let singleIdCode = singleIdCodeStr.split(";@;");
    selectedSatelliteId.value[i] = singleIdCode[0];
    if (selectedSatelliteCode.value === "") {
      selectedSatelliteCode.value = singleIdCode[1];
    } else {
      selectedSatelliteCode.value += ',' + singleIdCode[1];
    }
  }

  let contents = subSystemTypes.value;
  let len = contents.length;
  if (len !== 0) {
    return;
  }

  const params = {
    id: selectedSatelliteId.value[0],
  }


  InstructTypesSerive(params).then((resp) => {
    if (resp.code === 200) {
      subSystemTypes.value = resp.data;
      collapseKey.value++; // 关键：每次赋值后+1，强制el-collapse重新渲染

    } else {
      alert(resp.msg);
    }

  }).catch((error) => {
    alert(JSON.stringify(error))
  })
}

const getInstructList = () => {

  instructList.value = [];

  if ((activeName.value + "") === "") {
    return;
  }

  const params = {
    satelliteId: selectedSatelliteId.value[0],
    typesCode: activeName.value
  }
  getInstructionsOfTypeSerive(params).then((resp) => {

    if (resp.code === 200) {
      console.log(resp.data);
      instructList.value = resp.data;
    } else {
      alert(resp.msg);
    }

  }).catch((error) => {
    alert(JSON.stringify(error))
  })
  showInstruct.value = true;
}

const generateInstruction = (e, code, name) => {

  if (e.target.checked) {

    getInstructionContent(selectedSatelliteCode, code, tableData.length);

    let ck = e.target;
    let row = {
      satelliteData: selectedSatelliteCode.value,
      instructionCode: code,
      instructionName: name,
      instructionCodeName: code + '-' + name,
      instructionContent: "",
      checkbox: ck
    };
    addRow(row);
  } else {

    if (tableData.length > 0) {
      for (let i = 0; i < tableData.length; i++) {
        let row = tableData[i];
        if (code === row.instructionCode) {
          if (!confirm("确定删除第" + (i + 1) + " 行，编号和名称为 ' " + code + "-" + name + " ' 的指令数据吗？")) {
            e.target.checked = true;
            return;
          }
          tableData.splice(i, 1);
          // 新增：取消复选框删除行后重新初始化拖拽
          initSortable();
          break;
        }
      }
    }
  }

}

const addRow = (newRow) => {
  // 增加这两个字段
  newRow.showAbsoluteDelayPicker = false   // 是否弹出日期框
  newRow.absoluteDelayTime   = ''         // 绝对延时值
  // 新增：把当前时间写进去
  newRow.sendTime = new Date().toLocaleString();   // 或你要的任意格式
  let rowNum = tableData.push(newRow);
  dateShow.value[rowNum - 1] = false;
  // 新增：添加行后重新初始化拖拽
  initSortable();
};

const showDates = (checked, rowNum) => {

  if (checked) {
    dateShow.value[rowNum] = true;

  } else {
    dateShow.value[rowNum] = false;
  }
}

const getInstructionContent = (satelliteCodes, instructionCode, rowNum) => {

  console.log('调用获取指令方法时，传递的参数：', satelliteCodes, instructionCode, rowNum);

  let selectedSatellite = selectedSatelliteData.value + "";
  let satelliteIdCode = selectedSatellite.split(",");
  console.log('调用获取指令方法时，循环satelliteIdCode 的值：', satelliteIdCode);
  console.log(satelliteCodes, instructionCode, rowNum);
  let param_a = [];
  for (let i = 0; i < satelliteIdCode.length; i++) {
    let param_b = {};
    let singleIdCodeStr = satelliteIdCode[i];

    console.log('调用获取指令方法时，循环 singleIdCodeStr 的值：', singleIdCodeStr);
    let singleIdCode = singleIdCodeStr.split(";@;");
    console.log('调用获取指令方法时，循环 singleIdCode 的值：', singleIdCode);
    param_b.satelliteId = singleIdCode[0];
    param_b.scId = singleIdCode[1];
    param_b.instructionCode = instructionCode;
    param_b.satelliteCodes = satelliteCodes;
    console.log('调用获取指令方法时，循环 param_b 的值：', param_b);
    param_a.push(param_b);
  }
  console.log('调用获取指令方法时，循环 param_a 的值：', param_a);
  let params = {instructVoList: param_a}
// ShengChengZhiLingCodeSerive
//   getInstructionsOfTypeSerive(params).then((resp) => {
  ShengChengZhiLingCodeSerive(params).then((resp) => {
    console.log('接收返回结果resp： ', resp);
    if (resp.code === 200) {
      // instructionContent.value[rowNum] = dataJSON.data;
      tableData.forEach((item, index) => {
        // item 是当前元素，index 是索引
        // checkbox : input
        // instructionCode :  "TCTY0001"
        // instructionCodeName :  "TCTY0001-软件复位"
        // instructionContent : ""
        // instructionName :  "软件复位"
        // satelliteData :  "xxyz3280"

        console.log('每一个：', index, item);
        console.log('resp.data.list[0]：', resp.data[0]);
        if (item.instructionCode === resp.data[0].instructionCode) {
          item.instructionContent = resp.data[0].instructionContent
        }
        // 可以修改元素属性
        item.age += 1;
      });
      instructionContent.value[rowNum] = resp.data[0].instructionContent;
    } else {
      alert("错误代码：" + code + "; 错误消息：" + message);
    }
  }).catch((error) => {
    alert(error)
  })
}
// duoxingFaSongZhiLingSerive  多星发送指令
const handleSend = (row) => {
/*
  absoluteDelayTime: ""
  absoluteDelayTime:"2025-08-29 12:00:00"
  instructionCode: "TCTY0001"
  instructionCodeName: "TCTY0001-软件复位"
  instructionContent: "1ACFFC1D000112131301800210000000000100001103C001008335260000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020202020202021E1E1E1E1E1E1E1E1E1E1E1E1E00000000000000000000000000F407AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADBF0"
  instructionName: "软件复位"
  satelliteData: "0xA1"
  sendTime: "2025/8/26 15:55:33"
  showAbsoluteDelayPicker: true
  showAbsoluteDelayPicker: false
  */
  /** 卫星唯一标识 satelliteId */
  /** 轨道航天器设备编码 deviceCode */
  /** 指令系统代号  commandCode */
  /** 指令显示名称  commandName */
  /** 指令详细内容 commandContent */
  /** 指令码字/校验字 commandCodeword */
  /** 绝对延时(毫秒) absoluteDelay */
  // :satelliteIds="currentSatelliteIds"

  console.log(row);
  console.log(row.absoluteDelayTime);
  console.log(row.instructionCode);

  let params = {
    absoluteDelayTime: row.value.absoluteDelayTime,
    commandCode: row.value.instructionCode,
    commandName: row.value.instructionName,
    commandContent: row.value.instructionContent,
    satelliteIds: currentSatelliteIds.value,
    showAbsoluteDelayPicker: row.value.showAbsoluteDelayPicker,
    satelliteData: row.value.satelliteData,
  }
  console.log(params);
// ShengChengZhiLingCodeSerive
  duoxingFaSongZhiLingSerive(params).then((resp) => {
    console.log('接收返回结果resp： ', resp);
    if (resp.code === 200) {

    } else {
    }
  }).catch((error) => {
    alert(error)
  })



}
const handleDelete = (index, row) => {
  if (!confirm("确定删除第 " + (index + 1) + " 行，编号和名称为 ' " + row.instructionCodeName + " ' 的指令数据吗？")) {
    return;
  }
  tableData.splice(index, 1);
  let ck = row.checkbox;
  if (ck) {
    ck.checked = false;
  }
  // 新增：删除行后重新初始化拖拽
  initSortable();
}

const getSendHistory = (currentPage, pageSize) => {

  if (currentPage <= 0) {
    currentPage = 1;
  }
  if (pageSize <= 0) {
    pageSize = 10;
  }
  canProtocolListSerive(currentPage, pageSize).then(response => {
    historyData.value = response.data.data;
    totals.value = response.data.totals;
  }).catch((error) => {
    alert(JSON.stringify(error))
  })


  /*
  service.get('/apis/canProtocolList', {
    params: {
      currentPage: currentPage,
      pageSize: pageSize
    }

  }).then((resp) => {
    let result_str = JSON.stringify(resp.data);
    let resultJSON = JSON.parse(result_str);
    let data_str = JSON.stringify(resultJSON['data'] || resultJSON.data);
    let dataJSON = JSON.parse(data_str);
    let code = resultJSON['code'] || resultJSON.code;
    let message = resultJSON['message'] || resultJSON.message;
    if (code === "0") {
      historyData.value = dataJSON.records;
      totals.value = dataJSON.totals;
    } else {
      alert(message);
    }

  }).catch((error) => {
    alert(JSON.stringify(error))
  })
  */


};

// 处理每页数量变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  const newTotalPages = Math.ceil(totals.value / newSize);
  currentPage.value = Math.min(currentPage.value, newTotalPages) || 1;

  getSendHistory(currentPage.value, pageSize.value);
};

// 处理页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;

  getSendHistory(currentPage.value, pageSize.value);
};


</script>

<template>
  <div class="instruct-send-main">
    <div class="branch-types-left">
      <span class="instruct-search">
        <input type="text" style="width: 60%;border-radius: 6px;border-color: #bebebe;border-style: none"/>
        <el-button type="primary" :icon="Search" style="width: 20%;"/>
      </span>
      <el-select v-model="selectedSatelliteData" multiple placeholder="选择卫星" style="width: 90%"
                 @change="getSubSystemTypes()">
        <el-option
            v-for="item in satelliteList"
            :key="item.id"
            :label="item.name"
            :value="item.id + ';@;' + item.code">
        </el-option>
      </el-select>
      <p/>
      <span>全部指令</span>


      <el-scrollbar max-height="80%"
                    style="padding: 2px;
                    height: 500px;
                    padding: 0px;
                    background: white;
                  "
      >

        <el-collapse v-model="activeName" class="instruct-collapse" accordion @change="getInstructList()"
                     :key="collapseKey">
          <el-collapse-item
              v-for="(typeItem, typeIndex) in subSystemTypes"
              :title="typeItem.moduleName"
              :name="typeItem.typesCode"
              :key="typeIndex"
          >
            <div
                v-show="showInstruct"
                v-for="(instructItem, instructIndex) in instructList"
                :key="instructIndex"
                style="
                        display: flex;
                        align-items: center;      /* 垂直居中 */
                        margin-left: 10px;
                        gap: 6px;                 /* 元素间距 */
                      "
            >
              <!-- 复选框 -->
              <input
                  type="checkbox"
                  :value="instructItem.instructionCode"
                  @change="generateInstruction($event, instructItem.instructionCode, instructItem.instructionName)"
              />
              <!-- 指令代码 -->
              <span>{{ instructItem.instructionCode }}</span>
              <!-- 指令名称（超长省略） -->
              <span
                  style="
                          flex: 1 1 0;
                          white-space: nowrap;
                          overflow: hidden;
                          text-overflow: ellipsis;
                        "
                  :title="instructItem.instructionName"
              >
      {{ instructItem.instructionName }}
    </span>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-scrollbar>
    </div>
    <div class="send-instruct-right">
      <el-row style="position: relative;top: 0;height: 7.5%;min-height: 50px;">
        <el-col :span="24">
          <el-divider content-position="left">未发送</el-divider>
        </el-col>
      </el-row>
      <el-row style="position: relative;top: 0;height: 56%;max-height: 56%;min-height: 200px;">
        <el-col :span="24">
          <el-table ref="tableRef" :data="tableData" style="position:absolute;width: 100%;height: 100%;top: 0;border-radius: 8px;">
            <el-table-column label="序号" width="50">
              <template #default="scope">
                <div style="align-items: center">
                  <span style="margin-left: 0">{{ scope.$index + 1 }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="satelliteData" v-model="selectedSatelliteData" label="卫星" width="80">
            </el-table-column>
            <el-table-column prop="instructionCode" label="指令代号" width="0" v-if="false">
            </el-table-column>
            <el-table-column prop="instructionName" label="指令名称" width="0"
                             style="white-space: nowrap;text-overflow: ellipsis;" v-if="false">
            </el-table-column>
            <el-table-column prop="instructionCodeName" label="指令名称" width="160"
                             style="white-space: nowrap;text-overflow: ellipsis;">
            </el-table-column>

            <!--
                        <el-table-column prop="instructionContent" label="指令码字"></el-table-column>
            -->
            <!-- 指令码字列 - 添加了Tooltip和内容限制 -->
            <el-table-column prop="instructionContent" label="指令码字">
              <template #default="scope">
                <el-tooltip
                    :content="scope.row.instructionContent"
                    placement="top"
                    effect="dark"
                    :disabled="scope.row.instructionContent.length <= 200"
                ><!-- 内容较短时不显示tooltip -->
                  <div class="content-limit">
                    {{ scope.row.instructionContent }}
                  </div>
                </el-tooltip>
              </template>
            </el-table-column>


            <el-table-column prop="absoluteDelayed" label="绝对延时" width="220">
              <template #default="scope">
                <div style="display:flex;flex-direction: row;align-items: center">
                  <span style="margin-left: 0">
                    <!-- 勾选框：控制当前行的 showAbsoluteDelayPicker -->
                    <el-checkbox
                        v-model="scope.row.showAbsoluteDelayPicker"
                        style="margin-right:4px"/>
                  </span>
                  <!--   v-model="absoluteDelayed[ scope.$index ]"-->
                  <el-date-picker
                      v-if="scope.row.showAbsoluteDelayPicker"
                      v-model="scope.row.absoluteDelayTime"
                      type="datetime"
                      placeholder="选择日期"
                      format="YYYY-MM-DD hh:mm:ss"
                      value-format="YYYY-MM-DD hh:mm:ss"
                      style="width:180px">
                  </el-date-picker>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220">
              <template #default="scope">
                <div style="align-items: center;white-space: nowrap;">

                  <!-- 添加参数设置按钮 -->
                  <el-button
                      size="small"
                      type="primary"
                      @click="openParameterSettings(scope.row.instructionCode,scope.row.instructionName)"
                      plain
                  >
                    参数设置
                  </el-button>

                  <el-button type="success" size="small" @click="handleSend(scope.row)" plain>
                    发 送
                  </el-button>
                  <el-button
                      size="small"
                      type="danger"
                      @click="handleDelete(scope.$index, scope.row)" plain>
                    删 除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row style="position: relative;height: 7.5%;min-height: 50px;">
        <el-col :span="24">
          <el-divider content-position="left">已发送</el-divider>
        </el-col>
      </el-row>
      <el-row style="position: relative;top: 0;height: 28%;min-height: 100px">
        <el-col :span="24">
          <el-table style="position: relative;width: 100%;height: 70%;top: 0;border-radius: 8px">
            <el-table-column label="指令代号" width="200">
              <template #default="scope">
                <div style="align-items: center">
                  <span style="margin-left: 0">{{ scope.row.remoteControlProtocol }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="指令名称" min-width="400">
              <template #default="scope">
                <div style="align-items: center">
                  <span style="margin-left: 0">{{ scope.row.remoteControlTemplate }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="指令码字" min-width="400">
              <template #default="scope">
                <div style="align-items: center">
                  <span style="margin-left: 0">{{ scope.row.remoteControlTemplate }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="绝对延时" min-width="150">
              <template #default="scope">
                <div style="align-items: center">
                  <span style="margin-left: 0">{{ scope.row.remoteControlTemplate }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="发送时间" min-width="150">
              <template #default="scope">
                <div style="align-items: center">
                  <span style="margin-left: 0">{{ scope.row.remoteControlTemplate }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="180">
              <template #default="scope">
                <div style="align-items: center;white-space: nowrap;">
                  <el-button type="success" size="small" @click="handleSend(scope.row)" plain>
                    发 送
                  </el-button>
                  <el-button
                      size="small"
                      type="danger"
                      @click="handleDelete(scope.$index, scope.row)" plain>
                    删 除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              style="margin-top: 5px;margin-right: 3px;min-height: 50px;"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totals"/>
        </el-col>
      </el-row>
    </div>
  </div>


  <!-- 在适当位置添加参数设置对话框 -->
  <div>
    <ParameterSettings
        v-model:visible="parameterDialogVisible"
        :instructionCode="currentInstructionCode"
        :satelliteId="currentSatelliteId"
        :instructionName="currentInstructionName"
        :satelliteIds="currentSatelliteIds"
        :selectedSatelliteCodes="selectedSatelliteCodes"
        @saved="handleParametersSaved"
    />
  </div>
</template>

<style scoped>
.instruct-send-main {
  position: relative;
  width: 99%;
  height: 100%;
  margin-top: 0;
  margin-left: auto;
  margin-right: auto;

  border-radius: 10px;

  display: flex;
  flex-direction: row;
  justify-content: center;
}

.branch-types-left {
  position: absolute;
  width: 20%;
  height: 100%;
  top: 0;
  left: 0;

  border-color: #bebebe;
  border-top: 1px solid;
  border-left: 1px solid;
  border-bottom: 1px solid;
  border-radius: 8px;
}

.send-instruct-right {
  position: absolute;
  width: 80%;
  height: 98%;
  left: 20%;
  top: 0;
  right: 0;

  border: solid 1px #bebebe;
  border-radius: 8px;
}

.instruct-search {
  position: relative;
  width: 100%;
  margin-top: 10px;
  margin-bottom: 10px;

  display: flex;
  flex-direction: row;
  justify-content: space-around;
}

.instruct-collapse {
  position: relative;
  width: 100%;
  background-color: #f5f5f5;
}

.history-paging {
  position: relative;
  width: 96%;
  margin-top: 5px;
  right: 3px;
}

/* 控制指令码字列的内容显示长度 */
.content-limit {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  cursor: pointer; /* 鼠标变为指针，提示可查看完整内容 */
  padding: 0 4px; /* 增加一点内边距，避免内容太贴边 */
}

.sortable-ghost {
  opacity: 0.5;
  background-color: #c8ebfb;
}

</style>
